package com.mrxu.monitor.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.mrxu.monitor.base.ResultCode;
import com.mrxu.monitor.base.ResultObj;
import com.mrxu.monitor.config.MonitorProperties;
import com.mrxu.monitor.service.ReportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

import static com.mrxu.monitor.base.ResultObj.error;
import static com.mrxu.monitor.base.ResultObj.success;

@Controller
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
@RequestMapping("/"+MonitorProperties.MONITORPREFIX)
public class ReportController {

    @Autowired
    private ReportService reportService;

    @Autowired
    private MonitorProperties config;

    @Autowired
    private MonitorProperties monitorProperties;

    @ResponseBody
    @RequestMapping(value = "/pvUv.json",produces = "application/json;charset=UTF-8")
    public ResultObj<Object> pvUv(HttpServletRequest request) {
        ResultObj<Object> checkAuth = checkToken(request);
        if(checkAuth != null) {
            return checkAuth;
        }
        return success(reportService.pvUvHistory(30));
    }

    @ResponseBody
    @RequestMapping(value = "/statistics.json",produces = "application/json;charset=UTF-8")
    public ResultObj<Object> statistics(HttpServletRequest request) {
        ResultObj<Object> checkAuth = checkToken(request);
        if(checkAuth != null) {
            return checkAuth;
        }
        return success(reportService.getReport());
    }

    private ResultObj<Object> checkToken(HttpServletRequest request) {
        if(!monitorProperties.isEnable()) {
            return error("未开启api监控",ResultCode.ERR_NOT_AUTH.code);
        }
        String timestamp = request.getParameter("timestamp");
        if(StrUtil.isBlank(timestamp)) {
            return error("认证时间戳不能为空",ResultCode.ERR_NOT_AUTH.code);
        }
        long authTime = Long.valueOf(timestamp);
        long now = System.currentTimeMillis();
        if(Math.abs(now-authTime) > 1000*60*5) { // 前后5分钟有效
            return error("认证时间请取当前北京时间",ResultCode.ERR_NOT_AUTH.code);
        }
        String token = request.getParameter("token");
        if(!DigestUtil.md5Hex(timestamp+DigestUtil.md5Hex(config.getViewPassword())).equals(token)) {
            return error("密码错误",ResultCode.ERR_NOT_AUTH.code);
        }
        return null;
    }

}
